package com.net.xpay.web.controller.merchant.safePay;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.xpay.web.vo.ApplySafePayOrderReceiptVo;
import com.net.xpay.web.vo.SafePayOrderExportVo;
import com.net.xpay.web.vo.SafePayOrderVo;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.LocalDateUtil;
import com.net.common.util.SerializationUtil;
import com.net.xpay.alipay.enums.IdentityType;
import com.net.xpay.common.domain.SafePayOrderReceipt;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.enums.safePay.ApplyReceiptStatus;
import com.net.xpay.common.manager.SafePayOrderReceiptManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.domain.safePay.SafePayBatch;
import com.net.xpay.core.domain.safePay.SafePayOrder;
import com.net.xpay.core.manager.safePay.SafePayBatchManager;
import com.net.xpay.core.manager.safePay.SafePayOrderManager;
import com.net.xpay.core.model.IdModel;
import com.net.xpay.core.model.SafePayOrderSearchModel;
import com.net.xpay.core.service.safePay.SafePayReceiptService;
import com.net.xpay.core.utils.BeanCopierUtil;
import com.net.xpay.core.utils.JxlsUtils;
import com.net.xpay.web.secutiry.RequestUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2020/5/7 13:31

 */
@RestController
@Slf4j
@RequestMapping("/merchant/safe-pay-order")
@Api(tags = "商户/安全付手工打款明细", description = "商户 安全付手工打款明细 net")
public class SafePayOrderController {

    @Autowired
    private SafePayOrderManager safePayOrderManager;

    @Autowired
    private SafePayBatchManager safePayBatchManager;

    @Autowired
    private SafePayReceiptService safePayReceiptService;

    @Autowired
    private SafePayOrderReceiptManager safePayOrderReceiptManager;

    /**
     * 搜索
     */
    @ApiOperation("搜索")
    @PostMapping("/search")
    public ResultPagedList<SafePayOrderVo> search(@ApiIgnore @RequestUser User merchant, @RequestBody SafePayOrderSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        searchModel.setUserId(merchant.getId());

        List<SafePayOrder> payTransList = safePayOrderManager.search(searchModel);
        List<SafePayOrderVo> vos = BeanCopierUtil.batchCopy(SafePayOrder.class, SafePayOrderVo.class, payTransList);
        for (SafePayOrderVo vo : vos) {
            SafePayOrderReceipt receipt = safePayOrderReceiptManager.findBySafePayOrderId(vo.getUserId(), vo.getId());
            if (receipt != null) {
                vo.setReceiptDownloadUrl(receipt.getDownloadUrl());
                vo.setReceiptStatus(receipt.getStatus());
            }
        }


        long count = safePayOrderManager.searchCount(searchModel);

        return new ResultPagedList<>(vos, count, searchModel);
    }

    /**
     * 申请回单
     */
    @ApiOperation("申请回单")
    @PostMapping("/apply-receipt")
    public ResultData<ApplySafePayOrderReceiptVo> applyOrderReceipt(@ApiIgnore @RequestUser User merchant, @RequestBody IdModel idModel) {
        Preconditions.checkArgument(idModel != null && idModel.getId() != null);

        SafePayOrderReceipt receipt = safePayReceiptService.applySafePayOrderBillFile(merchant, idModel.getId());

        //目前发现回单生成很快，而且过期很快大概30秒，所以直接同步返回结果
        LocalDateTime deadline = LocalDateTime.now().plusSeconds(20L);
        while (LocalDateTime.now().isBefore(deadline)) {
            try {
                receipt = safePayReceiptService.updateReceiptFile(receipt.getId());
                if (receipt.getStatus() == ApplyReceiptStatus.SUCCESS) {
                    ApplySafePayOrderReceiptVo vo = new ApplySafePayOrderReceiptVo();
                    vo.setDownloadUrl(receipt.getDownloadUrl());
                    vo.setErrorMessage(receipt.getErrorMessage());
                    vo.setStatus(receipt.getStatus());
                    return new ResultData<>(vo);
                }
            } catch (Exception e) {
                log.warn("applyOrderReceipt error|id={}", idModel.getId(), e);
            }

        }
        //超时设置为失败，让重新下载
        receipt.setStatus(ApplyReceiptStatus.FAIL);
        safePayOrderReceiptManager.update(receipt);

        throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "下载超时，请稍后再试");
    }


    /**
     * 导出明细
     */
    @ApiOperation("导出明细")
    @GetMapping("/export")
    public ResultData<Boolean> exportSafePayOrder(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant, Long batchId) {
        Preconditions.checkArgument(batchId != null);
        SafePayBatch batch = safePayBatchManager.findById(merchant.getId(), batchId);
        List<SafePayOrder> orderList = safePayOrderManager.listByBatchId(merchant.getId(), batchId);

        // 定义一个Map，往里面放入要在模板中显示数据
        Map<String, Object> model = new HashMap<>();
        List<SafePayOrderExportVo> vos = BeanCopierUtil.batchCopy(SafePayOrder.class, SafePayOrderExportVo.class, orderList);
        vos.forEach(vo -> {
            if (IdentityType.ALIPAY_LOGON_ID.getValue().equals(vo.getIdentityType()))  {
                vo.setAccountType("支付宝账号");
            } else {
                vo.setAccountType("淘宝昵称");
            }

            vo.setDate(LocalDateUtil.getDateTimeAsString(vo.getCreateTime()));
        });
        model.put("payTrans", vos);
        model.put("batch", batch);

        String fileName = "安全付批次明细(" + batch.getImportBatchNo() + ").xlsx";
        String template = "/excel/tpl/安全付批次明细.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }
    /**
     * 导出单笔明细
     */
    @ApiOperation("导出单笔明细")
    @GetMapping("/export-detail")
    public ResultData<Boolean> exportPayTransDetail(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);
        SafePayOrderSearchModel searchModel = SerializationUtil.str2Object(searchModelJson, SafePayOrderSearchModel.class);
        searchModel.setUserId(merchant.getId());
        long totalCount = safePayOrderManager.searchCount(searchModel);
        if (totalCount > 10000L) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "导出明细超过1万条，无法导出");
        }
        List<SafePayOrder> safePayOrderList = safePayOrderManager.list(searchModel);

        // 定义一个Map，往里面放入要在模板中显示数据
        Map<String, Object> model = new HashMap<>();
        List<SafePayOrderExportVo> vos = BeanCopierUtil.batchCopy(SafePayOrder.class, SafePayOrderExportVo.class, safePayOrderList);
        vos.forEach(vo -> {
            vo.setDate(LocalDateUtil.getDateTimeAsString(vo.getCreateTime()));
        });
        model.put("safePayOrders", vos);

        String fileName = "安全转账明细.xlsx";
        String template = "/excel/tpl/安全转账明细.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }



}
